package com.saturn.action.system.dict.test;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.saturn.app.web.DictManager;
import com.saturn.app.web.IAction;
import com.saturn.app.web.IView;
import com.saturn.app.web.view.JsonView;

public class EditDictByTypeAction implements IAction {
	@Override
	public IView execute(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Map<String, String>> dicts = DictManager.get();

		return new JsonView(toJsonArray(
				dicts.get(request.getParameter("type")), request
						.getParameter("selectId")));
	}

	private String toJsonArray(Map<String, String> map, String selectId) {

		StringBuffer buffer = new StringBuffer();

		buffer.append("[");

		for (Map.Entry<String, String> entry : map.entrySet()) {
			if (selectId.equals(entry.getKey())) {
				buffer.append("{\"id\":" + entry.getKey() + ",");
				buffer.append("\"text\":" + "\"" + entry.getValue() + "\""
						+ ",");
				buffer.append("\"selected\":" + true + "},");
			} else {
				buffer.append("{\"id\":" + entry.getKey() + ",");
				buffer.append("\"text\":" + "\"" + entry.getValue() + "\""
						+ ",");
				buffer.append("\"selected\":" + false + "},");
			}

		}

		buffer.append("]");

		String json = buffer.toString().replaceFirst(",]", "]");
		return (json);
	}

	@Override
	public String requestMapping() {
		return "/system/dict/editDictByType.action";
	}
}
